<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>企业微信管理后台</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../css/reset.css">
    <link rel="stylesheet" href="../../css/fonts.css">
    <link rel="stylesheet" href="../../js/layui/css/layui.css">
    <link rel="stylesheet" href="../../js/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../js/data-tables/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="../../css/main.css">
</head>
<!-- 新客户欢迎语 -->

<body>
    <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
    <div class="config_welcome_word">
        <div class="header">
            <div class="back">返回</div>
            <div class="type_select_wrapper">添加入群欢迎语素材</div>
        </div>
        <div class="welcome_text_container">
            <div class="left_section">
                <div class="header_wrapper">
                    <div class="in_variable">
                        <span class="iconfont_box"><i class="iconfont icon-kehu1"></i></span>
                        <span class="text">插入客户昵称</span>
                    </div>
                    <div class="in_variable">
                        <span class="iconfont_box"><i class="iconfont icon-kehu1"></i></span>
                        <span class="text">插入客户昵称</span>
                    </div>
                </div>
                <div class="content_wrapper">
                    <div class="edit_wrapper">
                        <textarea class="welcome_content" name="welcome_content" id="welcome_content"
                            placeholder="如：你好，欢迎加入..." maxlength="100"></textarea>
                        <div class="underline"></div>
                        <div class="uploaded_image_box" style="display: none;">
                            <i class="iconfont icon-tupian"></i>
                            <span class="text">菱悦E客服.png</span>
                            <i class="iconfont icon-shanchu delete_upload_image"></i>
                        </div>
                        <div class="add_image_wrapper">
                            <div class="show_wrapper">
                                <i class="iconfont icon-ic_add"></i>
                                <span>添加图片</span>
                            </div>
                            <input class="add_image_input" type="file" name="add_image_input"
                                accept="image/png,image/jpeg">
                        </div>
                    </div>
                </div>
                <div class="area_wrapper">使用范围：全部成员</div>
                <div class="normal_btn submit_btn">保存</div>
            </div>

            <div class="right_section">
                <div class="show_box">
                    <div class="group_head">
                        <div class="group_name_box">
                            <span class="group_name">群聊名称(25)</span>
                            <img src="../../images/company_wechat_logo.png">
                        </div>
                    </div>
                    <div class="chat_container">
                        <div class="group_time">12:00</div>
                        <div class="chat_item real_chat">
                            <img class="left_avatar" src="../../images/test.JPG">
                            <div class="right_chat mock_chat_content">输入群欢迎语素材</div>
                        </div>
                        <div class="chat_item upload_box" style="display: none;">
                            <img class="left_avatar" src="../../images/test.JPG">
                            <div class="right_chat">
                                <img src="">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="../../js/jquery-3.3.1.min.js"></script>
    <script src="../../js/layui/layui.js"></script>
    <script src="../../js/bootstrap/js/bootstrap.min.js"></script>
    <script src="../../js/data-tables/jquery.dataTables.min.js"></script>
    <!-- 上传图片 -->
    <script src="../../js/exif.js"></script>
    <script src="../../js/addPerson_data/upload-image.js"></script>
    <script>
        //获取url中的参数
        function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg); //匹配目标参数
            if (r != null) return unescape(r[2]);
            return null; //返回参数值
        }
        let nav_index = getUrlParam('nav_index')
        let welcome_id = getUrlParam('id') // 拿到点击进来的id
        let welcome_content = decodeURI(getUrlParam('content')) // 拿到点击进来的欢迎语
        let welcome_imgSrc = getUrlParam('imgSrc') // 拿到点击进来的欢迎语图片服务器路径
        let welcome_imgName = decodeURI(getUrlParam('imgName')) // 拿到点击进来的欢迎语图片名称
        console.log(welcome_id, welcome_content, welcome_imgSrc, welcome_imgName)
        if (welcome_content) {
            if (welcome_imgSrc) {
                // 当文本存在 图片路径存在时
                $("#welcome_content").val(welcome_content.substring(0, welcome_content.length - 4))
                $(".mock_chat_content").text(welcome_content.substring(0, welcome_content.length - 4))
            } else {
                // 当文本存在 图片路径不存在时
                $("#welcome_content").val(welcome_content)
                $(".mock_chat_content").text(welcome_content)
            }
            
        }
        if (welcome_imgSrc) {
            // 当图片路径存在时
            $(".upload_box .right_chat img").attr('src', welcome_imgSrc)
            $(".uploaded_image_box .text").text(welcome_imgName)
            $(".uploaded_image_box .text").attr('data-src', welcome_imgSrc)
            $(".uploaded_image_box").show()
            $(".upload_box").show()
            $(".add_image_wrapper").hide()
        }
        // 实例化表单
        layui.use('form', function () {
            var form = layui.form;
            layui.use('layer', function () {
                var layer = layui.layer
                // 返回
                $(".back").click(function () {
                    self.location.href = "welcome-text-set.html?nav_index=" + nav_index + '&tab_index=1'
                })
                // 点击插入客户昵称
                $(".in_variable").click(function() {
                    let oldValue = $('#welcome_content').val()
                    let newValue = oldValue + '${nickname}'
                    $('#welcome_content').val(newValue)
                    $(".mock_chat_content").html(newValue)
                })
                // 监听内容输入框
                $('#welcome_content').keyup(
                    function () {

                        var remain = $(this).val().length;
                        if (remain > 100) {
                            layer.msg('字数超过限制')
                            return false
                        }
                        if (remain == 0) {
                            $('.mock_chat_content').html('输入群欢迎语素材');
                        } else {
                            $('.mock_chat_content').html($(this).val());
                        }
                    }
                );
                // 上传图片
                //将base64转换为文件
                function dataURLtoFile(dataurl, filename) {
                    var arr = dataurl.split(','),
                        mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]),
                        n = bstr.length,
                        u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new File([u8arr], filename, {
                        type: mime
                    });
                }
                $("input[name=add_image_input]").bind('change', function (e) {
                    let file = e.target.files[0];
                    if (file.size == 0) {
                        alert('照片上传失败，上传的照片无效');
                        $(this).val() == '';
                    } else {
                        console.log('image   ' + $(this).val());
                        //图片方向角 added by lzk
                        let Orientation = null;
                        let inputFileInfo = $(this).val();
                        let that = this;
                        //$("#loadingState").show();
                        //获取照片方向角属性，用户旋转控制
                        EXIF.getData(file, function () {
                            EXIF.getAllTags(this);
                            Orientation = EXIF.getTag(this, 'Orientation');
                            var reader1 = new FileReader();
                            var re = reader1.readAsDataURL(file);
                            var image = new Image();
                            //定义流对象事件
                            reader1.onload = function (e) {
                                image.src = this.result;
                            }
                            // 缩放图片需要的canvas
                            var canvas = document.createElement('canvas');
                            var context = canvas.getContext('2d');
                            // 定义image 事件
                            //base64地址图片加载完毕后
                            var compressoption = {
                                maxWidth: 400,
                                maxHeight: 400,
                                quality: 0.7
                            }
                            image.onload = function () {
                                //// 图片原始尺寸
                                var originWidth = this.width;
                                var originHeight = this.height;
                                // 最大尺寸限制
                                var maxWidth = compressoption.maxWidth || 400,
                                    maxHeight = compressoption.maxHeight || 400;
                                // 目标尺寸
                                var targetWidth = originWidth,
                                    targetHeight = originHeight;
                                // 图片尺寸超过400x400的限制
                                if (originWidth > maxWidth || originHeight > maxHeight) {
                                    if (originWidth / originHeight > maxWidth / maxHeight) {
                                        // 更宽，按照宽度限定尺寸
                                        targetWidth = maxWidth;
                                        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                                    } else {
                                        targetHeight = maxHeight;
                                        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                                    }
                                }
                                // canvas对图片进行缩放
                                canvas.width = targetWidth;
                                canvas.height = targetHeight;
                                // 清除画布
                                context.clearRect(0, 0, targetWidth, targetHeight);
                                // 图片压缩
                                context.drawImage(image, 0, 0, targetWidth, targetHeight);
                                //修复ios
                                var dataURL = "";
                                if (navigator.userAgent.match(/iphone/i)) {
                                    // console.log('iphone');
                                    //alert(expectWidth + ',' + expectHeight);
                                    //如果方向角不为1，都需要进行旋转 added by lzk
                                    if (Orientation != "" && Orientation != 1 && Orientation != undefined) {
                                        // alert('旋转处理');
                                        switch (Orientation) {
                                            case 6: //需要顺时针（向左）90度旋转
                                                // alert('需要顺时针（向左）90度旋转');
                                                rotateImg(this, 'left', canvas);
                                                break;
                                            case 8: //需要逆时针（向右）90度旋转
                                                // alert('需要顺时针（向右）90度旋转');
                                                rotateImg(this, 'right', canvas);
                                                break;
                                            case 3: //需要180度旋转
                                                // alert('需要180度旋转');
                                                rotateImg(this, 'right', canvas); //转两次
                                                rotateImg(this, 'right', canvas);
                                                break;
                                        }
                                    }
                                    dataURL = canvas.toDataURL("image/jpeg", 0.7);
                                } else if (navigator.userAgent.match(/Android/i)) { // 修复android
                                    dataURL = canvas.toDataURL(compressoption.mime || "image/jpeg", compressoption.quality || 0.7);
                                } else {
                                    //alert(Orientation);
                                    if (Orientation != "" && Orientation != 1 && Orientation != undefined) {
                                        //alert('旋转处理');
                                        switch (Orientation) {
                                            case 6: //需要顺时针（向左）90度旋转
                                                rotateImg(this, 'left', canvas);
                                                break;
                                            case 8: //需要逆时针（向右）90度旋转
                                                rotateImg(this, 'right', canvas);
                                                break;
                                            case 3: //需要180度旋转
                                                rotateImg(this, 'right', canvas); //转两次
                                                rotateImg(this, 'right', canvas);
                                                break;
                                        }
                                    }

                                    dataURL = canvas.toDataURL("image/jpeg", 0.9);
                                }
                                $(".upload_box .right_chat img").attr('src', dataURL) // 将上传的图片地址赋值给右边的框显示
                                $(".upload_box").show() // 图片在右边的框内显示
                                $(".uploaded_image_box .text").text(file.name) // 将图片的名称赋值给图片路径框
                                $(".uploaded_image_box").show() // 图片路径框显示
                                $(".add_image_wrapper").hide() // 添加图片隐藏
                                // canvas压缩并上传
                                var fileObject = dataURLtoFile(dataURL, file.name);
                                var formdata = new FormData();
                                formdata.append('fileType', 'img'); //文件格式
                                formdata.append('fileType_file', fileObject);
                                formdata.append('method', 'upload');
                                console.log('fileType_file', fileObject);
                                $("input[name=add_image_input]").val("");

                                // ajax请求成功后需要将上传至服务器的图片地址赋值给显示路径span上，在点击删除该路径时取图片地址使用
                                $(".uploaded_image_box .text").attr('data-src', 'src')

                                // 							$.ajax({
                                // 								url: "/Handle/Dis.ashx",
                                // 								method: 'POST',
                                // 								processData: false,
                                // 								contentType: false,
                                // 								cache: false,
                                // 								data: formdata
                                // 							}).done((response) => {
                                // 								let data = JSON.parse(response);
                                // 
                                // 								if (data.Result == true) {
                                // 									let path = data.Data[0].Path;
                                // 									var formdata2 = new FormData();
                                // 									formdata2.append('fileType', 'LSN');
                                // 									formdata2.append('fileType_file', path);
                                // 									formdata2.append('method', 'Distinguish');
                                // 									$.ajax({
                                // 										url: "/Handle/Dis.ashx",
                                // 										method: 'POST',
                                // 										processData: false,
                                // 										contentType: false,
                                // 										cache: false,
                                // 										data: formdata2
                                // 									}).done((response) => {
                                // 										$("#loadingState").hide();
                                // 										let data2 = JSON.parse(response);
                                // 										if (data2.Result == true) {
                                // 											let LSN = data2.Data;
                                // 											$("#Key").val(LSN);
                                // 											$("#search-btn-id").trigger("click");
                                // 										} else {
                                // 											alert(data2.Data);
                                // 										}
                                // 
                                // 									}).fail((err) => {
                                // 										console.log(err);
                                // 									})
                                // 								} else {
                                // 									alert('上传图片无效!请重新上传');
                                // 								}
                                // 
                                // 
                                // 							}).fail((err) => {
                                // 								console.log(err);
                                // 							})

                            }
                        });
                    }
                });

                // 隐藏上传图片框
                $(".delete_upload_image").click(function () {
                    let image_src = $(this).prev().attr('data-src') // 取到图片的路径
                    console.log(image_src)
                    // 当ajax请求完成 图片成功删除后 执行以下操作
                    $(".uploaded_image_box").hide() // 图片路径框显示
                    $(".add_image_wrapper").show() // 添加图片隐藏
                    $(".upload_box").hide()
                })

                // 保存入群欢迎语配置
                $(".submit_btn").click(function() {
                    let content = $("#welcome_content").val() // 拿到欢迎语文本
                    let imgSrc = $(".uploaded_image_box .text").attr('data-src') // 拿到上传图片路径 没有则为undefined
                    if (content.length == 0) {
                        layer.msg('文本内容不能为空')
                        return false
                    }
                    // 执行ajax请求
                    console.log(content, imgSrc)
                    // 请求成功后
                    layer.msg('保存成功')
                    setTimeout(() => {
                        self.location.href = "welcome-text-set.html?nav_index=" + nav_index + '&tab_index=1'
                    }, 1500)
                })
            })

        });

    </script>
</body>

</html>